package com.briup.service.impl;

import com.briup.bean.Customer;
import com.briup.dao.CustomerMapper;
import com.briup.service.ICustomerService;
import com.briup.util.MyBatisSqlSessionFactory;
import org.apache.commons.lang3.StringUtils;

/**
 * @author 王若龙
 * @CreateTime 2022-09-22 11:07
 */
public class ICustomerServiceImpl implements ICustomerService {

    private CustomerMapper customerMapper = MyBatisSqlSessionFactory
            .openSession(true)
            .getMapper(CustomerMapper.class);

    @Override
    public void register(Customer customer) {
        if (StringUtils.isAnyEmpty(customer.getName(), customer.getPassword(),
                customer.getAddress(), customer.getEmail(), customer.getTelephone(), customer.getZipCode())) {
            throw new RuntimeException("请求参数为空");
        }
        Customer customerByName = findCustomerByName(customer.getName());
        if (customerByName == null) {
            customerMapper.saveCustomer(customer);
        } else {
            throw new RuntimeException("用户名已存在");
        }
    }

    @Override
    public Customer findCustomerByName(String name) {
       return customerMapper.findCustomerByName(name);
    }

    @Override
    public Customer login(String name, String password) {
        if (StringUtils.isAnyEmpty(name, password)) {
            throw new RuntimeException("请求参数为空");
        }

        Customer customerByName = findCustomerByName(name);
        if (customerByName == null){
            throw new RuntimeException("用户名不存在");
        }
        if (password.equals(customerByName.getPassword())){
            return customerByName;
        }
        throw new RuntimeException("用户名或密码错误");
    }
}
